// pages/create_ticket/tickets.js
import request from "../../utils/request.js";
import themeManager from "../../utils/theme.js";

Page(themeManager.enhancePage({
  data: {
    reply: null,
    currentTheme: 'dark',
    feedbackTypes: [
      { value: 0, label: '设备报修' },
      { value: 1, label: '系统问题' },
      { value: 2, label: '意见建议' }
    ],
    feedbackTypeIndex: 0,
    deviceList: [],
    deviceIndex: 0,
    title: '',
    content: '',
    canSubmit: false
  },

  onLoad: function(options) {
    this.loadDeviceList();
    this.setData({feedbackTypeIndex: options.operation || 0});
  },

  // 加载设备列表
  loadDeviceList: function() {
    request
      .get("/devices/my_devices")
      .then((res) => {
        if (res && res.data && res.data.items) {
          const deviceList = res.data.items.map(device => ({
            ...device,
            display_name: device.nickname || device.device_id
          }));
          this.setData({
            deviceList: deviceList
          });
        }
      })
      .catch((err) => {
        console.error("加载设备列表失败:", err);
      });
  },

  // 反馈类型选择
  onFeedbackTypeChange: function(e) {
    const index = parseInt(e.detail.value);
    this.setData({
      feedbackTypeIndex: index
    });
    this.checkCanSubmit();
  },

  // 设备选择
  onDeviceChange: function(e) {
    const index = parseInt(e.detail.value);
    this.setData({
      deviceIndex: index
    });
    this.checkCanSubmit();
  },

  // 标题输入
  onTitleInput: function(e) {
    this.setData({
      title: e.detail.value
    });
    this.checkCanSubmit();
  },

  // 内容输入
  onContentInput: function(e) {
    this.setData({
      content: e.detail.value
    });
    this.checkCanSubmit();
  },

  // 检查是否可以提交
  checkCanSubmit: function() {
    const { feedbackTypeIndex, deviceList, deviceIndex, title, content } = this.data;
    let canSubmit = false;

    // 标题和内容都不能为空
    if (title.trim().length > 0 && content.trim().length > 0) {
      // 如果是设备报修，需要选择设备
      if (feedbackTypeIndex === 0) {
        canSubmit = deviceList.length > 0 && deviceIndex >= 0;
      } else {
        // 其他类型不需要选择设备
        canSubmit = true;
      }
    }

    this.setData({
      canSubmit: canSubmit
    });
  },

  // 提交工单
  submitTicket: function(e) {
    const { feedbackTypes, feedbackTypeIndex, deviceList, deviceIndex, title, content } = this.data;
    
    if (!this.data.canSubmit) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    const feedbackType = feedbackTypes[feedbackTypeIndex];
    const ticketData = {
      title: title.trim(),
      feedback_type: feedbackType.value,
      content: content.trim(),
      created_at: new Date().toISOString()
    };

    // 如果是设备报修，添加设备信息
    if (feedbackTypeIndex === 0 && deviceList.length > 0) {
      const selectedDevice = deviceList[deviceIndex];
      ticketData.device_uuid = selectedDevice.uuid;
    }

    console.log('提交工单数据:', ticketData);

    request.post('/tickets', ticketData)
      .then(res => {
        wx.showToast({
          title: '提交成功', 
          icon: 'success' 
        });
        
        // 清空表单
        this.setData({
          title: '',
          content: '',
          feedbackTypeIndex: 0,
          deviceIndex: 0,
          canSubmit: false
        });

        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1000);
      })
      .catch(err => {
        console.error('提交工单失败:', err);
        wx.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        });
      });
  }
}));